package com.rico.kok.controller.post;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rico.kok.entity.Post;
import com.rico.kok.entity.User;
import com.rico.kok.entity.povos.PostUser;
import com.rico.kok.service.interf.FollowService;
import com.rico.kok.service.interf.PostService;
import com.rico.kok.service.interf.UserService;
import com.rico.kok.tool.MessageUtils;
import com.rico.kok.tool.RegisterUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：Rico_Skipper(JinYang Han)
 * @Date：2022/5/1 15:20
 */
@Controller
public class UserController {

    //异常消息
    @Autowired
    MessageUtils messageUtils;

    //关注
    @Autowired
    FollowService followService;

    //作者
    @Autowired
    UserService userService;

    //内容
    @Autowired
    PostService postService;

    @Autowired
    RegisterUtils registerUtils;

    //访问作者空间
    @RequestMapping("/browseUser.htm")
    public String visitAuthor(@RequestParam(value = "num", defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "id", defaultValue = "1") Integer id,
                              HttpSession session,
                              Model model) {
        User user = new User();
        user.setUserId(id);
        List<User> list = userService.selectUsers(user);
        if (list == null || list.size() == 0) {
            messageUtils.setMsg(model, "错误", "用户消失了", "error");
            return "msg";
        }
        user = list.get(0);
        Post post = new Post();
        post.setUserId(id);
        PageHelper.startPage(pageNum, 6, "post_id desc");
        List<PostUser> postUsers = postService.selectPosts(post);
        PageInfo<PostUser> pageInfo = new PageInfo<>(postUsers);
        //判定是否关注用户
        follow(model, session, id);
        String url = "/browseUser.htm?id=" + id + "&num=";
        model.addAttribute("url", url);
        model.addAttribute("visitUser", user);
        model.addAttribute("pageInfo", pageInfo);
        return "post/browse_user";
    }

    //访问个人空间
    @RequiresRoles("user")
    @RequestMapping("/browserMyself.htm")
    public String myself(@RequestParam(value = "num", defaultValue = "1") Integer pageNum, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "login";
        }
        Post post = new Post();
        post.setUserId(user.getUserId());
        PageHelper.startPage(pageNum, 6, "post_id desc");
        ArrayList<PostUser> postUsers = postService.selectPosts(post);
        PageInfo<PostUser> pageInfo = new PageInfo<>(postUsers);
        String url = "/browserMyself.htm?num=";
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("url", url);
        return "post/browse_myself";
    }

    //进行修改个人信息
    @RequiresRoles("user")
    @RequestMapping("/editInformation.htm")
    public String editInformation(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "login";
        }
        model.addAttribute("editUser", user);
        return "editInfo";
    }

    //处理修改的个人信息
    @RequiresRoles("user")
    @PostMapping("/resolveInformation.htm")
    public String resolveInformation(User user, MultipartFile pic, HttpSession session, Model model) {
        //当前user的信息
        User inUser = (User) session.getAttribute("user");
        //需要更新的数据拼装
        User updateUser = new User();
        //修改了用户名
        if (user.getUserName() != null && !inUser.getUserName().equals(user.getUserName())) {
            //校验用户名长度
            if (user.getUserName().length() > 26) {
                messageUtils.setMsg(model, "失败", "你这名字多少有点长。", "error");
                return "msg";
            }
            updateUser.setUserName(user.getUserName());
        }
        //修改了密码
        if (user.getUserPassword() != null && !inUser.getUserPassword().equals(user.getUserPassword())) {
            //校验密码长度
            if (user.getUserPassword().length() > 50) {
                messageUtils.setMsg(model, "失败", "这么长的密码？没必要吧？", "error");
                return "msg";
            }
            updateUser.setUserPassword(user.getUserPassword());
        }

        //修改了头像
        String filename = null;
        if (pic != null) {
            long filesize = pic.getSize();
            //控制文件上传的大小 10MB 10*1024*1024
            if (filesize < 1024 * 1024 * 10) {
                String type = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf(".") + 1);
                switch (type) {
                    case "png":
                    case "jpg":
                    case "jpeg":
                        filename = registerUtils.updateFile(pic);
                    default:
                        break;
                }
            }
        }
        updateUser.setUserImage(filename);

        //修改了性别
        if (user.getUserGender() != null && !inUser.getUserGender().equals(user.getUserGender())) {
            updateUser.setUserGender(user.getUserGender());
        }
        //修改了生日
        if (user.getUserBirthday() != null && !inUser.getUserBirthday().equals(user.getUserBirthday())) {
            updateUser.setUserBirthday(user.getUserBirthday());
        }
        //修改了个人描述
        if (user.getUserDetail() != null && !inUser.getUserDetail().equals(user.getUserDetail())) {
            updateUser.setUserDetail(user.getUserDetail());
        }
        updateUser.setUserId(inUser.getUserId());
        userService.updateUser(updateUser);
        List<User> list = userService.selectUsers(updateUser);
        User newUser = list.get(0);
        session.setAttribute("user",newUser);
        return "redirect:/browserMyself.htm";
    }

    //判定用户是否是自己并判断是否关注用户
    private void follow(Model model, HttpSession session, Integer visitId) {
        //默认用户访问的不是自己
        model.addAttribute("itsMe", false);
        //判定是否登录
        if (session.getAttribute("user") != null) {
            model.addAttribute("userId", visitId);
            //登录后判断是否关注用户
            User user = (User) session.getAttribute("user");
            int isFollow = followService.selectAllFollowsId(user.getUserId()).indexOf(visitId);
            //判定是否是用户自己
            if (visitId.equals(user.getUserId())) {
                model.addAttribute("itsMe", true);
            }
            if (isFollow == -1) {
                model.addAttribute("isFollow", false);
            } else {
                model.addAttribute("isFollow", true);
            }
        } else {
            //未登录设置未登录
            model.addAttribute("isFollow", false);
        }
    }
}
